package com.yoke.controller.sysadmin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.common.JsonMessage;
import com.yoke.common.base.RewriteBaseControl;
import com.yoke.service.rewrite.ConfService;
import com.yoke.service.rewrite.EditRewriteServer;
import com.yoke.service.rewrite.RewriteIndexService;
import com.yoke.system.log.LogType;
import com.yoke.system.log.SystemLog;
import com.yoke.util.FileUtil;
import com.yoke.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by jiangzeyin on 2017/5/10.
 */
@Controller
@RequestMapping("sysadmin")
public class EditRewriteControl extends RewriteBaseControl {
    @Resource
    ConfService confService;

    @Resource
    EditRewriteServer editRewriteServer;

    @Resource
    RewriteIndexService rewriteIndexService;

    /**
     * 添加跳转
     *
     * @param name
     * @param parent
     * @return
     */
    @RequestMapping(value = "add_rewrite.html", produces = MediaType.TEXT_HTML_VALUE)
    public String add_rewrite(String name, String parent) {
        name = convertFilePath(name);
        parent = convertFilePath(parent);
        File file = new File(rewriteIndexService.getConfFile(), parent + "/" + name);
        if (!file.exists()) {
            request.setAttribute("tip", "不存在该信息");
            return "sysadmin/edit_rewrite";
        }
        request.setAttribute("name", name);
        request.setAttribute("parent", parent);
        request.setAttribute("add", true);
        return "sysadmin/edit_rewrite";
    }

    @RequestMapping(value = "recovery_rewrite.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String recovery_rewrite(String tag, String name, String parent) {
        name = convertFilePath(name);
        parent = convertFilePath(parent);
        File file = new File(rewriteIndexService.getConfFile(), parent + "/" + name);
        if (!file.exists() || file.isDirectory()) {
            return JsonMessage.getString(100, "不存在该信息");
        }
        tag = StringUtil.convertNULL(tag);
        File locFile = new File(file.getParent(), name.replace(".conf", ".rewrite_log"));
        if (!locFile.exists())
            return JsonMessage.getString(100, "不存在该信息,请勿错误操作");
        try {
            List<String[]> rLogs = confService.getRewritesLog(locFile.getPath());
            if (rLogs != null)
                for (String[] item : rLogs) {
                    String rurl = item[1];
                    String ltag = item[0];
                    if (tag.equals(ltag)) {
//                        String tag = url.replace("//", "");
//                        tag = tag.substring(tag.indexOf("/"), tag.length());
                        editRewriteServer.saveRewrite(tag, file.getPath(), tag, rurl, item[2], Boolean.valueOf(item[3]), Boolean.valueOf(item[4]));
                        reloadNginx("恢复" + rurl + " 跳转");
                        return JsonMessage.getString(200, "恢复成功");
                    }
                }
            return JsonMessage.getString(100, "没有找到该跳转信息");
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("异常", e);
            return JsonMessage.getString(100, "读取失败，请联系管理员");
        }
    }

    /**
     * 取消跳转
     *
     * @param tag
     * @param name
     * @param parent
     * @return
     */
    @RequestMapping(value = "cancel_rewrite.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_rewrite(String tag, String name, String parent) {
        name = convertFilePath(name);
        parent = convertFilePath(parent);
        tag = StringUtil.convertNULL(tag);
        File file = new File(rewriteIndexService.getConfFile(), parent + "/" + name);
        if (!file.exists() || file.isDirectory()) {
            return JsonMessage.getString(100, "不存在该信息");
        }
        if (tag.startsWith("http://")) {
            List<String> serviceName;
            try {
                serviceName = confService.getServiceName(file.getPath());
            } catch (IOException e) {
                SystemLog.LOG(LogType.CONTROL_ERROR).error("异常", e);
                return JsonMessage.getString(100, "处理信息失败");
            }
            if (serviceName == null || serviceName.size() <= 0)
                return JsonMessage.getString(100, "数据错误");
            for (String item : serviceName) {
                item = "http://" + item;
                if (tag.startsWith(item)) {
                    tag = tag.substring(item.length());
                    break;
                }
            }
        }
        //System.out.println(tag);
        boolean urlAll = true;
        try {
            List<String[]> logs = confService.getRewritesLog(file.getPath());
            if (logs != null)
                for (String[] item : logs) {
                    if (tag.equals(item[0])) {
                        urlAll = Boolean.valueOf(item[3]);
                        break;
                    }
                }
        } catch (IOException e) {
            e.printStackTrace();
            return JsonMessage.getString(100, "操作失败，请联系管理员,获取日志信息失败");
        }
        StringBuffer stringBuffer = editRewriteServer.delRewrite(tag, file.getPath(), urlAll);
        if (stringBuffer == null)
            return JsonMessage.getString(100, "操作失败，请联系管理员");
        try {
            FileUtil.writeFile(file.getPath(), stringBuffer);
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("异常", e);
            return JsonMessage.getString(100, "操作失败，请联系管理员");
        }
        reloadNginx("取消" + parent + "/" + name + "  " + tag + " 跳转");
        return JsonMessage.getString(200, "取消成功");
    }

    /**
     * 保存跳转
     *
     * @param name
     * @param parent
     * @param url
     * @param toUrl
     * @param url_all
     * @param send_par
     * @return
     */
    @RequestMapping(value = "save_rewrite.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_rewrite(String name, String tag, String parent, String url, String toUrl, String url_all, String send_par) {
        name = convertFilePath(name);
        parent = convertFilePath(parent);
        File file = new File(rewriteIndexService.getConfFile(), parent + "/" + name);
        url = FileUtil.ClearPath(StringUtil.convertNULL(url));
        if (!file.exists()) {
            return JsonMessage.getString(100, "不存在该信息");
        }
        JSONObject jsonObject;
        try {
            jsonObject = confService.getRewrites(file.getPath(), true, true);
        } catch (IOException e) {
            e.printStackTrace();
            return JsonMessage.getString(100, "读取信息失败，请联系管理员");
        }
        JSONArray jsonArray = jsonObject.getJSONArray("server_name");
        String server_name_url = null;
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            server_name_url = "http://" + jsonArray.getString(i);
            if (url.startsWith(server_name_url)) {
                break;
            }
            server_name_url = null;
        }
//        if (url.startsWith("http://"))
//            url = url.substring(6);
        if (server_name_url == null)
            return JsonMessage.getString(100, "请正确输入要跳转的链接");
        int url_all_int = StringUtil.parseInt(url_all, 0);
        String toLoc = url.replace(server_name_url, "");
        String oldLoc = StringUtil.IsEmpty(tag) ? toLoc.substring(0, toLoc.lastIndexOf("/") + 1) : tag;
        if (url_all_int == 1)
            toLoc = toLoc.substring(0, toLoc.lastIndexOf("/") + 1);
        if ("/".equals(toLoc))
            return JsonMessage.getString(100, "根路径，请不要开启全匹配");
//        if (!oldLoc.endsWith("/") && !oldLoc.endsWith(".html"))
//            oldLoc = oldLoc + "/";
        List<String[]> logs;
        try {
            String logName = file.getName().replace(".conf", ".rewrite_log");
            logs = confService.getRewritesLog(file.getParent() + "/" + logName);
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("异常", e);
            return JsonMessage.getString(100, "获取日志记录，失败，请联系管理员");
        }
        if (logs != null) {
            for (String[] item : logs) {
                if (!item[0].endsWith(".html") && toLoc.startsWith(item[0]) && !item[0].equals(oldLoc)) {
                    if (Boolean.valueOf(item[3])) {
                        return JsonMessage.getString(100, "该路径存在全匹配");
                    }
                }
            }
        }
        try {
            editRewriteServer.saveRewrite(oldLoc, file.getPath(), toLoc, url, toUrl, url_all_int == 1, StringUtil.parseInt(send_par) == 1);
        } catch (IOException e) {
            e.printStackTrace();
            return JsonMessage.getString(100, "保存失败，请及时联系管理员");
        }
        reloadNginx("保存" + parent + "/  " + name + url + " 跳转到：" + toUrl);
        return JsonMessage.getString(200, "保存成功");
    }


    /**
     * 修改跳转
     *
     * @param tag
     * @return
     */
    @RequestMapping(value = "edit_rewrite.html", produces = MediaType.TEXT_HTML_VALUE)
    public String edit_rewrite(String tag, String name, String parent) {
        name = convertFilePath(name);
        parent = convertFilePath(parent);
        tag = StringUtil.convertNULL(tag);
        File file = new File(rewriteIndexService.getConfFile(), parent + "/" + name);
        if (!file.exists() || file.isDirectory()) {
            request.setAttribute("tip", "不存在该信息");
            return "sysadmin/edit_rewrite";
        }
        try {
            JSONObject jsonObject = confService.getRewrites(file.getPath(), true, false);
            List<String[]> rewrite_logs = jsonObject.getObject("rewrite_logs", List.class);
            if (rewrite_logs == null || rewrite_logs.size() <= 0) {
                String res = backWay(jsonObject, tag, name, parent);
                if (res != null)
                    return res;
                request.setAttribute("tip", "数据错误，对应log null,请联系管理员");
                //return JsonMessage.getString(100, );
                return "sysadmin/edit_rewrite";
            }
            for (String[] item : rewrite_logs) {
                boolean find;
                if (tag.startsWith("http://")) {
                    find = item[1].equals(tag);
                } else {
                    find = item[0].equals(tag);
                }
                if (find) {
                    request.setAttribute("url", item[1]);
                    request.setAttribute("toUrl", item[2]);
                    request.setAttribute("name", name);
                    request.setAttribute("parent", parent);
                    request.setAttribute("tag", item[0]);
                    if (Boolean.valueOf(item[3]))
                        request.setAttribute("url_all", true);
                    if (Boolean.valueOf(item[4]))
                        request.setAttribute("send_par", true);
                    return "sysadmin/edit_rewrite";
                }
            }
            String res = backWay(jsonObject, tag, name, parent);
            if (res != null)
                return res;
            request.setAttribute("tip", "数据错误，没有找到对应log,请联系管理员");
            return "sysadmin/edit_rewrite";

            //request.setAttribute("tip", "没有找到对应数据");
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("异常", e);
            request.setAttribute("tip", "获取失败");
            return "sysadmin/edit_rewrite";
        }
        //return "rewrite/edit_rewrite";
    }

    private String backWay(JSONObject jsonObject, String tag, String name, String parent) {
        List<String[]> list = jsonObject.getObject("rewrites", List.class);
        if (list == null || list.size() <= 0) {
            request.setAttribute("tip", "没有数据,rew");
            return "sysadmin/edit_rewrite";
        }
        JSONArray server_name = jsonObject.getJSONArray("server_name");
        for (String[] item : list) {
            if (item[0].equals(tag)) {
                request.setAttribute("url", String.format("http://%s%s", server_name.getString(0), item[0]));
                request.setAttribute("toUrl", item[1]);
                request.setAttribute("name", name);
                request.setAttribute("parent", parent);
                request.setAttribute("tag", item[0]);
                return "sysadmin/edit_rewrite";
            }
        }
        return null;
    }
}
